package com.pingao.mp.modular.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pingao.mp.config.dict.DictConfig;
import com.pingao.mp.modular.sys.entity.Role;
import com.pingao.mp.modular.sys.entity.User;
import com.pingao.mp.modular.sys.service.RoleService;
import com.pingao.mp.modular.sys.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 闻品高
 * @since 2018-09-26
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Autowired
    private DictConfig dictConfig;

    @PostMapping("/login")
    public Object login(String userName, String password, Integer rememberMe) {
        return userService.login(userName, password, rememberMe);
    }

    @GetMapping("/list")
    public Object list(@RequestParam("pageNumber") Integer pageNumber,
                       @RequestParam("pageSize") Integer pageSize,
                       @RequestParam(value = "searchText", required = false) String searchText,
                       @RequestParam("sortName") String sortName,
                       @RequestParam("sortOrder") String sortOrder,
                       @RequestParam(value = "roleIds[]", required = false) List<Long> roleIds,
                       @RequestParam(value = "gender[]", required = false) List<Integer> gender,
                       @RequestParam(value = "name", required = false) String name,
                       @RequestParam(value = "nick", required = false) String nick,
                       HttpServletRequest request
    ) {
        return userService.getUserList(pageNumber, pageSize, searchText, sortName, sortOrder, roleIds, gender, name, nick);
    }

    @GetMapping("/roles")
    public Object roles() {
        return roleService.list(new QueryWrapper<Role>().select(Role.COL_ID, Role.COL_NAME));
    }

    @GetMapping("/genders")
    public Object genders() {
        return dictConfig.getGenders();
    }

    @GetMapping("/get")
    public Object get(@RequestParam(value = "id") Long id) {
        return userService.get(id);
    }

    @GetMapping("/delete")
    public Object delete(@RequestParam(value = "id") Long id) {
        return userService.get(id);
    }

    @PostMapping("/add")
    public Object add(User user) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", false);
        map.put("msg", "添加失败");
        int count = userService.count(new QueryWrapper<User>().and(q -> q.eq(User.COL_NAME, user.getName()).or().eq(User.COL_EMAIL, user.getEmail())));
        if (count > 0) {
            map.put("msg", "请检查用户名或邮箱是否已经存在");
        } else {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
            boolean b = userService.save(user);
            if (b) {
                map.put("status", true);
                map.put("msg", "添加成功");
            }
            map.put("user", user);
        }

        return map;
    }

    @GetMapping("/userExist")
    public Object userExist(@RequestParam(value = "name") String name, @RequestParam(value = "id", required = false) Long id) {
        Map<String, Object> map = new HashMap<>();
        int total = userService.count(new QueryWrapper<User>().eq("name", name).isNull("delete_time").ne(id != null, User.COL_ID, id));
        if (total > 0) {
            map.put("valid", false);
        } else {
            map.put("valid", true);
        }
        return map;
    }

    @GetMapping("/emailExist")
    public Object emailExist(@RequestParam(value = "email") String email, @RequestParam(value = "id", required = false) Long id) {
        Map<String, Object> map = new HashMap<>();
        int total = userService.count(new QueryWrapper<User>().eq("email", email).isNull("delete_time").ne(id != null, User.COL_ID, id));

        if (total > 0) {
            map.put("valid", false);
        } else {
            map.put("valid", true);
        }

        return map;
    }

    @DeleteMapping("/delete")
    public Object delete(
            @RequestParam(value = "ids") String ids
    ) {
        String[] split = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        for (String id : split) {
            if (id.equals("1")) {
                continue;
            }
            User u = userService.getById(id);
            if (u != null) {
                u.setDeleteTime(LocalDateTime.now());
                u.updateById();
            }
        }
        map.put("status", true);
        map.put("msg", "删除成功");
        map.put("ids", ids);
        return map;
    }

    @PostMapping("/edit")
    public Object edit(User user) {
        Map<String, Object> map = new HashMap<>();
        int count = userService.count(new QueryWrapper<User>().and(q -> q.eq(User.COL_NAME, user.getName()).or().eq(User.COL_EMAIL, user.getEmail())).ne(User.COL_ID, user.getId()));
        if (count > 0) {
            map.put("status", false);
            map.put("msg", "请检查用户名或邮箱是否已经存在于其他用户");
        } else {
            user.setUpdateTime(LocalDateTime.now());
            if (!user.getPassword().equals("")) {
                user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
            } else {
                user.setPassword(null);
            }
            if (!userService.updateById(user)) {
                map.put("status", false);
                map.put("msg", "保存用户出错......");
                return map;
            }
            map.put("status", true);
            map.put("msg", "保存用户成功");
            map.put("user", user);
        }
        return map;
    }

    @PostMapping("/myInfo")
    public Object myInfo(User user) {
        return userService.myInfo(user);
    }
}
